/**
* Author: fulishang
* Create Time  : 2016年8月14日,下午11:59:47
* Modify Time :
* Desc  : 
*/
package com.sam.si.dc;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.filters.CompositeFileListFilter;
import org.springframework.messaging.MessageChannel;

import com.sam.si.dc.filter.FileFilter;
import com.sam.si.dc.init.InitializeConfig;
import com.sam.si.dc.processor.DCProcessor;
import com.sam.si.dc.transformer.FileTransformer;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class DCBootstraper {
	
	@Value("${dc.input.file.directory}")
	String inputDir;
	

	public static void main(String[] args) throws IOException, InterruptedException {
		SpringApplication.run(DCBootstraper.class, args);
	}
	
	@Bean
	public IntegrationFlow processFileFlow() throws Exception {
		return IntegrationFlows.from("fileInputChannel").transform(fileTransformer())
				.handle("dcProcessor", "process").get();
	}

	@Bean
	public MessageChannel fileInputChannel() {
		return new DirectChannel();
	}

	@Bean
	@InboundChannelAdapter(value = "fileInputChannel", poller = @Poller(fixedDelay="5000"))//poll every 5 seconds
	public MessageSource<File> fileReadingMessageSource() {
		CompositeFileListFilter<File> filters = new CompositeFileListFilter<>();
		filters.addFilter(new FileFilter());

		FileReadingMessageSource source = new FileReadingMessageSource();
		source.setAutoCreateDirectory(true);
		source.setDirectory(new File(inputDir));
		source.setFilter(filters);

		return source;
	}
	
	@Bean
	public FileTransformer fileTransformer() throws Exception{
		
		return new FileTransformer(initializeConfig().initFileCatalogs(), initializeConfig().initFields());
	}

	@Bean
	public DCProcessor dcProcessor() {
		return new DCProcessor();
	}
	
	@Bean
	public InitializeConfig initializeConfig() {
		return new InitializeConfig();
	}
	
}
